#!/usr/bin/env ruby

require 'nokogiri'

class XmlUtil
  
  attr_accessor :doc, :path, :info, :version
  
  def initialize(doc = nil)
    if doc.class == Nokogiri::XML::Document
      @doc = doc
    elsif  doc.class == ''.class
      loadDoc(doc)
    end
  end

  def loadDoc(path=@path)
    file = File.open(path)
    if File.exist?(path)
      @doc = Nokogiri::XML(File.open(@path=path))
      return true
    end
    false
  end

  def isDoc?
    return true if @doc.class == Nokogiri::XML::Document
    false
  end

  def info
    Hash["name"=>name,"revision"=>version,"type"=>type]
  end

  def name
    node=@doc.xpath('//@name')[0]
    if node == nil
      @doc.child["name"]=type
      node=@doc.xpath('//@name')[0]
    end
    node.content
  end
  
  def type
    path.split("/")[-1][0..-5].downcase
  end
  
  def versionNode
    @node=@doc.xpath('//@version')[0] if @node == nil
    if @node == nil
      @doc.child["version"]=""
      @node=@doc.xpath('//@version')[0]
    end
    @node
  end

  def version
    @version=Version.new(versionNode.content) if @version==nil
    @version
  end

  def version=(vers)
    if @version==nil
      @version=Version.new(vers) 
    else
      @version.version=vers
    end
    versionNode.content=@version.to_s
    @version
  end

  def push
    File.open(path,'w'){|f| f.write(@doc.to_xml)} if isDoc?
    info
  end
  
  def to_s
    info.to_s
  end
end